﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Data;
using DR5.SPExtend;

namespace DR5.SPExtend
{
    /// <summary>
    /// Used for exporting of file, bascially .csv file, but can be used for other types as well.
    /// </summary>
    public class CSVExporter
    {
        private HttpResponse _response;
        public HttpResponse Response
        {
            set
            {
                _response = value;
            }
        }

        public void PreWriteToCSV(string fileName)
        {
            string attachment = "attachment; filename="+fileName+".csv";
            _response.Clear();
            _response.ClearHeaders();
            _response.ClearContent();
            _response.AddHeader("content-disposition", attachment);
            _response.ContentType = "text/csv";
            _response.AddHeader("Pragma", "public");
        }

        public void WriteRow(string[] strArray)
        {
            StringBuilder stringBuilder = new StringBuilder();

            foreach (string str in strArray)
            {
                AddComma(str, stringBuilder);
            }

            _response.Write(stringBuilder.ToString());
            _response.Write(Environment.NewLine);
        }

        public void WriteRow(object[] strArray)
        {
            StringBuilder stringBuilder = new StringBuilder();

            foreach (object str in strArray)
            {
                AddComma(str.ToString(), stringBuilder);
            }

            _response.Write(stringBuilder.ToString());
            _response.Write(Environment.NewLine);
        }

        public void WriteRow(string commaSepStr)
        {
            _response.Write(commaSepStr);
            _response.Write(Environment.NewLine);
        }

        public void PostWriteToCSV()
        {
            _response.End();
        }

        private void AddComma(string value, StringBuilder stringBuilder)
        {
            stringBuilder.Append(value.Replace(',', ' '));
            stringBuilder.Append(", ");
        }

        public void ExportDataTable(DataTable dt)
        {
            PreWriteToCSV(dt.TableName);
            WriteRow(dt.Columns.CommaSeparatedString(","));

            foreach (DataRow dr in dt.Rows)
            {
                object[] str = dr.ItemArray;
                WriteRow(str);
            }

            PostWriteToCSV();
        }
    }
}
